package ip.controller;
/***********************************************************************
 * Module:  GetAllLanguagesController.java
 * Author:  mojsilo
 * Purpose: Defines the Class GetAllLanguagesController
 ***********************************************************************/

import ip.command.GetLanguagesCommand;
import ip.dto.UserDTO;
import ip.exceptions.ApplicationException;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * @web.servlet
 * 	name="GetLanguagesController"
 * @web.servlet-mapping
 * 	url-pattern="/control/Languages"
 */
public class GetLanguagesController extends HttpServlet
{
	
	private static final long serialVersionUID = -4466696207015586509L;
	private Logger logger = Logger.getLogger(this.getClass());

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try{	
			logger.info("doGet()");
			UserDTO adminFromSession;
			HttpSession session = request.getSession(true);
			adminFromSession = (UserDTO) session.getAttribute("administrator");

			if(adminFromSession == null){
				response.sendRedirect(response.encodeRedirectURL("../jsp/login_administrator.jsp"));
				return;
			}
			
			GetLanguagesCommand getLanguagesCommand;

			getLanguagesCommand = new GetLanguagesCommand();
			getLanguagesCommand.init();
			getLanguagesCommand.execute();
			getLanguagesCommand.dispose();
			logger.debug("doGet(...) - getLanguagesCommand.getLanguages(): "+getLanguagesCommand.getLanguages());
			if (getLanguagesCommand.getLanguages()!= null){
				request.setAttribute("languages", getLanguagesCommand.getLanguages());
				getServletContext().getRequestDispatcher("/WEB-INF/jsp/administrator/languages.jsp").forward(request, response);
			}
			else
				getServletContext().getRequestDispatcher("/WEB-INF/jsp/administrator/add_language.jsp").forward(request, response);

		}
		catch (ApplicationException e) {
			logger.error(e);
			request.setAttribute("error", e.getMessage());
			getServletConfig().getServletContext().getRequestDispatcher("/WEB-INF/jsp/administrator/error.jsp").forward(request, response);
		}
		catch (Exception e) {
			logger.error(e);
			request.setAttribute("error", "Unexpected error!!");//kako ovo bolje odraditi???
			getServletConfig().getServletContext().getRequestDispatcher("/WEB-INF/jsp/administrator/error.jsp").forward(request, response);
		}	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		logger.info("doPost()");
		doGet(request, response);
	}

}